﻿using DevExpress.XtraEditors.Container;
using DevExpress.XtraGrid;
using DevExpress.XtraTreeList;
using DevExpress.XtraVerticalGrid;
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace Inaction.UI.Common
{
    public static class ControlHelper
    {
        public static List<T> FindControls<T>(Control control, Func<T, bool> filter = null) where T : Control
        {
            var list = new List<T>();
            FindControls<T>(list, control, filter);
            return list;
        }

        private static void FindControls<T>(List<T> list, Control control, Func<T, bool> filter = null) where T : Control
        {
            foreach (Control c in control.Controls)
            {
                if (c is T)
                {
                    T t = c as T;
                    if (filter == null || filter(t))
                    {
                        list.Add(t);
                    }
                }
                FindControls<T>(list, c, filter);
            }
        }

        public static void ExportToExcelFile(EditorContainer editorContainer)
        {
            if (editorContainer == null) return;
            var dialog = new SaveFileDialog();
            dialog.Filter = "Excel文件|*.xlsx";
            dialog.FileName = editorContainer.Name + ".xlsx";
            var result = dialog.ShowDialog();
            if (result == DialogResult.Cancel || string.IsNullOrEmpty(dialog.FileName)) return;
            var fileName = dialog.FileName;
            if (editorContainer is GridControl)
            {
                var grid = editorContainer as GridControl;
                grid.ExportToXlsx(fileName);
            }
            else if (editorContainer is TreeList)
            {
                (editorContainer as TreeList).ExportToXlsx(fileName);
            }

            else if (editorContainer is VGridControl)
            {
                (editorContainer as VGridControl).ExportToXlsx(fileName);
            }
        }
    }
}